/**
 * 上传管理器
 * 管理多个文件的上传任务
 */
class UploadManager {
    constructor(options = {}) {
        this.baseUrl = options.baseUrl || '/api/notebook/environment';
        this.chunkSize = options.chunkSize || 2 * 1024 * 1024; // 2MB
        this.maxConcurrent = options.maxConcurrent || 3; // 最大并发上传数
        this.allowedTypes = options.allowedTypes || []; // 允许的文件类型
        this.maxFileSize = options.maxFileSize || 100 * 1024 * 1024; // 100MB
        
        this.uploadTasks = new Map(); // 存储上传任务
        this.activeUploads = 0; // 当前活跃上传数
        this.uploadQueue = []; // 上传队列
        
        // 事件回调
        this.onTaskStart = options.onTaskStart || (() => {});
        this.onTaskProgress = options.onTaskProgress || (() => {});
        this.onTaskComplete = options.onTaskComplete || (() => {});
        this.onTaskError = options.onTaskError || (() => {});
        this.onQueueUpdate = options.onQueueUpdate || (() => {});
    }

    /**
     * 添加文件到上传队列
     */
    addFiles(files, options = {}) {
        const tasks = [];
        
        Array.from(files).forEach(file => {
            // 验证文件
            const validation = ChunkUploader.validateFile(file, this.allowedTypes, this.maxFileSize);
            
            if (!validation.valid) {
                this.onTaskError({
                    file,
                    errors: validation.errors
                });
                return;
            }

            // 创建上传任务
            const taskId = this.generateTaskId();
            const task = {
                id: taskId,
                file,
                options: { ...options },
                status: 'pending',
                progress: 0,
                uploadedChunks: 0,
                totalChunks: 0,
                fileId: null,
                error: null,
                startTime: null,
                endTime: null,
                uploader: null
            };

            this.uploadTasks.set(taskId, task);
            this.uploadQueue.push(taskId);
            tasks.push(task);
        });

        this.onQueueUpdate({
            queue: this.getQueueStatus(),
            tasks: this.getAllTasks()
        });

        // 开始处理队列
        this.processQueue();
        
        return tasks;
    }

    /**
     * 生成任务ID
     */
    generateTaskId() {
        return 'task_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }

    /**
     * 处理上传队列
     */
    async processQueue() {
        while (this.uploadQueue.length > 0 && this.activeUploads < this.maxConcurrent) {
            const taskId = this.uploadQueue.shift();
            const task = this.uploadTasks.get(taskId);
            
            if (task && task.status === 'pending') {
                this.startUpload(task);
            }
        }
    }

    /**
     * 开始上传任务
     */
    async startUpload(task) {
        this.activeUploads++;
        task.status = 'uploading';
        task.startTime = Date.now();

        // 创建上传器
        task.uploader = new ChunkUploader({
            baseUrl: this.baseUrl,
            chunkSize: this.chunkSize,
            onProgress: (progress) => {
                task.progress = progress.progress;
                task.uploadedChunks = progress.uploadedChunks;
                task.totalChunks = progress.totalChunks;
                
                this.onTaskProgress({
                    taskId: task.id,
                    ...task,
                    ...progress
                });
            },
            onStatusUpdate: (status) => {
                task.fileId = status.fileId;
                
                this.onTaskProgress({
                    taskId: task.id,
                    ...task,
                    status: status.status
                });
            },
            onSuccess: (result) => {
                task.status = 'completed';
                task.endTime = Date.now();
                task.progress = 100;
                
                this.onTaskComplete({
                    taskId: task.id,
                    ...task,
                    result
                });
                
                this.finishUpload(task);
            },
            onError: (error) => {
                task.status = 'failed';
                task.endTime = Date.now();
                task.error = error.error;
                
                this.onTaskError({
                    taskId: task.id,
                    ...task,
                    error: error.error
                });
                
                this.finishUpload(task);
            }
        });

        this.onTaskStart({
            taskId: task.id,
            ...task
        });

        try {
            await task.uploader.upload(task.file, task.options);
        } catch (error) {
            // 错误已在uploader的onError中处理
        }
    }

    /**
     * 完成上传任务
     */
    finishUpload(task) {
        this.activeUploads--;
        
        this.onQueueUpdate({
            queue: this.getQueueStatus(),
            tasks: this.getAllTasks()
        });
        
        // 继续处理队列
        this.processQueue();
    }

    /**
     * 取消上传任务
     */
    cancelTask(taskId) {
        const task = this.uploadTasks.get(taskId);
        if (!task) return false;

        if (task.status === 'pending') {
            // 从队列中移除
            const queueIndex = this.uploadQueue.indexOf(taskId);
            if (queueIndex > -1) {
                this.uploadQueue.splice(queueIndex, 1);
            }
        }

        task.status = 'cancelled';
        task.endTime = Date.now();

        this.onTaskError({
            taskId: task.id,
            ...task,
            error: '用户取消上传'
        });

        this.onQueueUpdate({
            queue: this.getQueueStatus(),
            tasks: this.getAllTasks()
        });

        return true;
    }

    /**
     * 重试失败的任务
     */
    retryTask(taskId) {
        const task = this.uploadTasks.get(taskId);
        if (!task || task.status !== 'failed') return false;

        task.status = 'pending';
        task.progress = 0;
        task.uploadedChunks = 0;
        task.error = null;
        task.startTime = null;
        task.endTime = null;
        task.uploader = null;

        this.uploadQueue.push(taskId);
        this.processQueue();

        return true;
    }

    /**
     * 清除已完成的任务
     */
    clearCompleted() {
        const completedTasks = [];
        
        this.uploadTasks.forEach((task, taskId) => {
            if (task.status === 'completed' || task.status === 'cancelled') {
                completedTasks.push(taskId);
            }
        });

        completedTasks.forEach(taskId => {
            this.uploadTasks.delete(taskId);
        });

        this.onQueueUpdate({
            queue: this.getQueueStatus(),
            tasks: this.getAllTasks()
        });

        return completedTasks.length;
    }

    /**
     * 获取队列状态
     */
    getQueueStatus() {
        return {
            pending: this.uploadQueue.length,
            active: this.activeUploads,
            total: this.uploadTasks.size
        };
    }

    /**
     * 获取所有任务
     */
    getAllTasks() {
        return Array.from(this.uploadTasks.values()).sort((a, b) => {
            if (a.startTime && b.startTime) {
                return b.startTime - a.startTime;
            }
            return 0;
        });
    }

    /**
     * 获取任务统计
     */
    getStatistics() {
        const tasks = this.getAllTasks();
        const stats = {
            total: tasks.length,
            pending: 0,
            uploading: 0,
            completed: 0,
            failed: 0,
            cancelled: 0,
            totalSize: 0,
            uploadedSize: 0
        };

        tasks.forEach(task => {
            stats[task.status]++;
            stats.totalSize += task.file.size;
            
            if (task.status === 'completed') {
                stats.uploadedSize += task.file.size;
            } else if (task.status === 'uploading') {
                stats.uploadedSize += Math.floor(task.file.size * (task.progress / 100));
            }
        });

        return stats;
    }

    /**
     * 暂停所有上传
     */
    pauseAll() {
        // 注意：这里只是清空队列，正在上传的任务无法暂停
        this.uploadQueue.length = 0;
        
        this.onQueueUpdate({
            queue: this.getQueueStatus(),
            tasks: this.getAllTasks()
        });
    }

    /**
     * 恢复所有上传
     */
    resumeAll() {
        const pendingTasks = this.getAllTasks().filter(task => task.status === 'pending');
        
        pendingTasks.forEach(task => {
            if (!this.uploadQueue.includes(task.id)) {
                this.uploadQueue.push(task.id);
            }
        });

        this.processQueue();
    }
}

// 导出类
if (typeof module !== 'undefined' && module.exports) {
    module.exports = UploadManager;
} else {
    window.UploadManager = UploadManager;
}

